<template>
  <BasicModal @register="registerModal" v-bind="$attrs" wrapClassName="form-modal">
    <template #title>
      <div class="step-form-form">
        <a href="http://glcs.51wit.com/" target="_blank">
          <img src="/src/assets/images/design/logo.png" />
        </a>
        <span>•</span>
        <span>{{ t('表单设计') }} - {{ t('数据优先') }}</span>
        <a-steps :current="current">
          <a-step :title="t('基础信息')" />
          <a-step :title="t('表单设计')" />
          <a-step :title="t('表单事件')" />
        </a-steps>
        <div class="btn-box">
          <a-button type="primary" @click="handleStepPrev" v-show="current !== 0">{{
            t('上一步')
          }}</a-button>
          <a-button type="primary" @click="handleStepNext" v-show="current < 2">{{
            t('下一步')
          }}</a-button>
          <a-button type="primary" @click="handleSave" v-show="current === 2">{{
            t('保存')
          }}</a-button>
          <a-button type="primary" danger @click="handleClose">{{ t('关闭') }}</a-button>
        </div>
      </div>
    </template>
    <div class="step-container">
      <BasicConfigStep ref="basicConfigStepRef" v-show="current === 0" />
      <FormDesignStep ref="formDesignStepRef" v-show="current === 1" />
      <FormEventStep ref="formEventStepRef" v-show="current === 2" />
    </div>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, reactive, provide, watch, Ref, toRaw } from 'vue';
  import BasicConfigStep from '../BasicConfigStep.vue';
  import { FormDesignStep, FormEventStep } from '/@/components/CreateCodeStep';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { CustomFormConfig, GeneratorConfig } from '/@/model/generator/generatorConfig';
  import { TableInfo } from '/@/components/Designer';
  import {
    addDataFirstFormTemplate,
    updateDataFirstFormTemplate,
    getFormTemplate,
  } from '/@/api/form/design';
  import { FormTypeEnum } from '/@/enums/formtypeEnum';
  import * as antd from '/@/components/Designer/src/types';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  const current = ref(0);

  const basicConfigStepRef = ref();
  const formDesignStepRef = ref();
  const formEventStepRef = ref();

  const tableInfo = ref<TableInfo[]>([]);
  const widgetForm = ref(JSON.parse(JSON.stringify(antd.widgetForm)));
  const isUpdate = ref<boolean>(false);
  const formId = ref<string>('');
  const emits = defineEmits(['success', 'register', 'close']);

  let generatorConfig = reactive<GeneratorConfig>({
    databaseId: '', //数据库id
    tableConfigs: [],
    formJson: {},
    formEventConfig: {},
    isDataAuth: false,
    dataAuthList: [],
  });
  let customFormConfig = reactive<CustomFormConfig>({
    name: '',
    category: '',
    formDesignType: 0,
    formType: FormTypeEnum.CUSTOM_FORM,
    formJson: generatorConfig,
    remark: '',
  });

  provide<GeneratorConfig>('generatorConfig', generatorConfig);
  provide<CustomFormConfig>('customFormConfig', customFormConfig);
  provide<Ref<TableInfo[]>>('tableInfo', tableInfo);
  provide<string>('designType', 'data');
  provide('widgetForm', widgetForm);
  provide<Ref<number>>('current', current); //当前步骤
  provide<boolean>('isCustomForm', true); //是自定义表单

  watch(
    () => generatorConfig,
    (val) => {
      customFormConfig.formJson = val;
    },
    {
      deep: true,
    },
  );

  const [registerModal, { setModalProps, closeModal }] = useModalInner((data) => {
    isUpdate.value = !!data.isUpdate;
    formId.value = data.id;
    if (formId.value) getFormTemplateInfo();
    setModalProps({
      confirmLoading: false,
      canFullscreen: false,
      defaultFullscreen: true,
      destroyOnClose: true,
      draggable: false,
      showOkBtn: false,
      showCancelBtn: false,
      footer: null,
      closable: false,
    });
  });

  async function getFormTemplateInfo() {
    const data = await getFormTemplate(formId.value);
    customFormConfig.name = data.name;
    customFormConfig.category = data.category;
    customFormConfig.formDesignType = data.formDesignType;
    customFormConfig.formJson = JSON.parse(data.formJson);
    customFormConfig.remark = data.remark;

    const { formJson } = customFormConfig;

    generatorConfig.databaseId = formJson.databaseId;
    generatorConfig.isDataAuth = formJson.isDataAuth;
    generatorConfig.dataAuthList = formJson.dataAuthList;
    generatorConfig.tableConfigs = formJson.tableConfigs;
    generatorConfig.formJson = formJson.formJson;
    generatorConfig.formEventConfig = formJson.formEventConfig!;
    generatorConfig.formJson.list = generatorConfig.formJson.list.filter(
      (x) => x.type !== 'hiddenComponent',
    );
    widgetForm.value = generatorConfig.formJson;
    basicConfigStepRef.value.setFieldsValue({
      name: customFormConfig?.name,
      category: customFormConfig?.category,
      remark: customFormConfig?.remark,
      databaseId: generatorConfig.databaseId,
      isDataAuth: generatorConfig.isDataAuth,
      dataAuthList: generatorConfig.dataAuthList,
    });
  }

  function handleClose() {
    closeModal();
    emits('close');
  }

  //上一步
  function handleStepPrev() {
    current.value--;
  }
  //下一步
  async function handleStepNext() {
    const isOk = await stepValidate[current.value]();
    if (!isOk) {
      return;
    }
    current.value++;
  }

  async function handleSave() {
    const isOk = await stepValidate[2]();
    if (!isOk) {
      return;
    }
    if (
      generatorConfig.formJson?.hiddenComponent &&
      generatorConfig.formJson?.hiddenComponent.length
    ) {
      generatorConfig.formJson.list.push(...generatorConfig.formJson.hiddenComponent);
    }
    if (isUpdate.value) {
      await updateDataFirstFormTemplate({ id: formId.value, ...toRaw(customFormConfig) });
    } else {
      await addDataFirstFormTemplate(toRaw(customFormConfig));
    }

    closeModal();
    emits('close');
    emits('success');
  }

  const stepValidate = {
    //数据表配置 验证
    0: () => basicConfigStepRef.value.validateStep(),
    1: () => formDesignStepRef.value.validateStep(),
    2: () => formEventStepRef.value.validateStep(),
  };
</script>
<style lang="less" scoped>
  @keyframes rotation {
    from {
      transform: rotate(0deg);
    }

    to {
      transform: rotate(360deg);
    }
  }
  @keyframes rotationReverse {
    from {
      transform: rotate(0deg);
    }

    to {
      transform: rotate(-360deg);
    }
  }

  :deep(.ant-steps-item-process) {
    .ant-steps-item-icon {
      border: 2px solid #fff;
      line-height: 30px;
      animation: rotation 4s linear infinite;
      position: relative;

      &::before {
        border: 2px dashed #1890ff;
        content: '';
        width: 36px;
        height: 36px;
        display: block;
        border-radius: 50%;
        position: absolute;
        left: -4px;
        top: -4px;
      }

      .ant-steps-icon {
        display: inline-block;
        animation: rotationReverse 4s linear infinite;
      }
    }
  }

  .step-form-content {
    padding: 24px;
    background-color: @component-background;
  }

  .step-form-form {
    display: flex;
    align-items: center;
    font-weight: 400;

    a {
      margin-left: -16px;
    }

    span {
      font-size: 16px;
      margin: 0 20px 0 -5px;
      white-space: nowrap;
    }

    :deep(.ant-steps) {
      width: calc(100% - 750px);
    }

    :deep(.ant-steps-item-container) {
      padding: 3px 0 3px 3px;
    }

    .btn-box {
      position: absolute;
      right: 10px;

      :deep(.ant-btn) {
        margin-right: 10px;
      }
    }
  }

  .step-container {
    height: calc(100% - 50px);
  }

  .step1 {
    padding: 14px;
    box-sizing: border-box;
  }
</style>
